﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ReportWizard.Controls
{
    class AutoCompleteTextBox : TextBox
    {
        public List<string> Items;
        private bool _controlKey;

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if (e.KeyChar == (int)Keys.Escape)
            {
                this.Text = string.Empty;
                _controlKey = true;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                _controlKey = true;
            }
            else
            {
                _controlKey = false;
            }
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            if (!string.IsNullOrEmpty(this.Text) && !_controlKey && Items != null)
            {
                string matchText = this.Text;
                string matchString = Items.Find(s => s.StartsWith(matchText));
                if (!string.IsNullOrEmpty(matchString))
                {
                    this.SelectionStart = matchText.Length;
                    this.SelectionLength = this.Text.Length - this.SelectionStart;
                }
            }
        }
    }
}
